<?php
namespace Orm\ArticleContent;

use Base\Exception\RmException;
class ArticleContentClass extends \Base\BaseOrmObject{
    protected   $id,
				$article_id = 0, // 文章ID
				$type = 0, // （文章内容类型）1文字 2视频, 3 音频 ,4图片
				$content = '', // 存放内容
				$sort = 0, // 商品排序
				$is_del = 0, // 默认0  是否删除 1是 0否
				$insert_time = '', // 插入时间
				$update_time = ''; // 更新时间

    const TYPE_TEXT = 1; // 文本  插入，更新是 htmlencode, 查询时 htmldecode
    const TYPE_VIDEO = 2; //视频
    const TYPE_AUDIO = 3; // 音频
    const TYPE_IMG = 4; // 图片
    const TYPE_PRODUCT = 5; // 商品

    function __init($data)
    {
        parent::__init($data);
        $this->dformat($data);
    }

    private function dformat()
    {
        if ($this->type == self::TYPE_TEXT) {
            $this->type = html_entity_decode($this->type);
        }
    }

    public function loadById($id = 0)
    {
        $model = new \Orm\ArticleContent\ArticleContentModel();
        $data = $model->loadById($id);
        self::__init($data);
    }

    public function loadArticleImg($article_id = 0)
    {
        $model = new \Orm\ArticleContent\ArticleContentModel();
        return $model->loadArticleImg($article_id);
    }

    public function insert()
    {
        if ($this->type == self::TYPE_TEXT) {
            $this->type = htmlentities($this->type);
        }
        $this->checkNecessaryParam();
        $data = array(
            'article_id' => $this->article_id,
			'type' => $this->type,
			'content' => $this->content,
			'sort' => $this->sort,
        );

        $model = new \Orm\ArticleContent\ArticleContentModel();
        $model->insert($data);
        $this->id = $model->getLastId();
    }

    public function update()
    {
        if ($this->type == self::TYPE_TEXT) {
            $this->type = htmlentities($this->type);
        }
        $this->checkNecessaryParam();
        $data = array(
            'article_id' => $this->article_id,
			'type' => $this->type,
			'content' => $this->content,
			'sort' => $this->sort,
        );

        $model = new \Orm\ArticleContent\ArticleContentModel();
        $model->update($data, "`id` = {$this->id}");
    }

    public function delete($id)
    {
        $data = array('is_del'=>1);
        $model = new \Orm\ArticleContent\ArticleContentModel();
        $model->update($data, "`id` = {$id}");
    }

    private function checkNecessaryParam()
    {
        if (intval($this->article_id) == 0) throw new \Exception('对不起，请选择文章');
    }
}